﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace ET.Monitor.DAL
{
    public class TextBoxDAL
    {
        string strSql = "", strErrMsg = "";
        object obj = null;
        DataTable dt = new DataTable();
        IList<Hashtable> list = new List<Hashtable>();

        InvokeWebService iw = new InvokeWebService();
        string rtdbRelationAddress = "";
        string rtdbRealTimeAddress = "";
        string rtdbNameSpace = "";
        string rtdbJudge = "";

        public TextBoxDAL()
        {
            rtdbRelationAddress = ConfigurationManager.ConnectionStrings["RelationURL"].ConnectionString;
            rtdbRealTimeAddress = ConfigurationManager.ConnectionStrings["RealTimeURL"].ConnectionString;
            rtdbNameSpace = ConfigurationManager.ConnectionStrings["NameSpace"].ConnectionString;
            rtdbJudge = ConfigurationManager.ConnectionStrings["Judge"].ConnectionString;
        }

        #region UTC
        public static int DateTimeToUTC(DateTime DT)
        {
            long a = new DateTime(1970, 1, 1, 0, 0, 0, 0).Ticks;
            int rtnInt = 0;
            rtnInt = (int)((DT.Ticks - 8 * 3600 * 1e7 - a) / 1e7);
            return rtnInt;
        }
        #endregion

        #region 一段时间电压
        public double[] GetVoltage(string id, DateTime st, DateTime et, int count)
        {
            strSql = "select T_VoltageTAG from T_BASE_POINTS_COMBINEBOX where T_BOXID='" + id + "'";
            obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });

            double[] val = null;

            if (obj != null && obj != DBNull.Value)
                val = (double[])iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValueByStep", new object[] { obj.ToString(), st, et, count });
            return val;
            //dt = (DataTable)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValueByStartTimeAndEndTime", new object[] { obj.ToString(), Convert.ToDateTime(st), Convert.ToDateTime(et) });
            //int num = 0;
            //if (dt.Rows.Count < count)
            //{
            //    num = 1;
            //}
            //else
            //{
            //    num = dt.Rows.Count / count;
            //}
            //ArrayList arrList = new ArrayList();
            //DateTime _sTime = new DateTime(1970, 1, 1);
            //int dtCount = dt.Rows.Count;

            ////for (int i = 0; i < dt.Rows.Count; i++)//倒序
            //for (int i = dtCount - 1; i > -1; i--)
            //{
            //    if (i % num == 0)
            //    {
            //        if (dt.Rows[i]["VALUE"].ToString() == "")
            //        {
            //            continue;
            //        }
            //        ArrayList arr = new ArrayList();
            //        string timeStamp = DateTimeToUTC(Convert.ToDateTime(dt.Rows[i]["TIME"].ToString())).ToString();
            //        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            //        long lTime = long.Parse(timeStamp + "0000000");
            //        TimeSpan toNow = new TimeSpan(lTime);
            //        DateTime dtResult = dtStart.Add(toNow);

            //        arr.Add(Convert.ToInt64((dtResult - _sTime).TotalMilliseconds.ToString()));
            //        arr.Add(Math.Round(Convert.ToDouble(dt.Rows[i]["VALUE"]), 2));
            //        arrList.Add(arr);
            //    }
            //}
            //return arrList;
        }
        #endregion

        #region 一段时间电流
        public double[] GetCurrent(string id, DateTime st, DateTime et, int count)
        {
            strSql = "select T_CURRENTTAG from T_BASE_POINTS_COMBINEBOX where T_BOXID='" + id + "'";
            obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            double[] val = null;

            if (obj != null && obj != DBNull.Value)
                val = (double[])iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValueByStep", new object[] { obj.ToString(), st, et, count });
            return val;
            //dt = (DataTable)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValueByStartTimeAndEndTime", new object[] { obj.ToString(), Convert.ToDateTime(st), Convert.ToDateTime(et) });
            //int num = 0;
            //if (dt.Rows.Count < count)
            //{
            //    num = 1;
            //}
            //else
            //{
            //    num = dt.Rows.Count / count;
            //}
            //ArrayList arrList = new ArrayList();
            //DateTime _sTime = new DateTime(1970, 1, 1);
            //int dtCount = dt.Rows.Count;
            ////for (int i = 0; i < dt.Rows.Count; i++)
            //for (int i = dtCount - 1; i > -1; i--)
            //{
            //    if (i % num == 0)
            //    {
            //        if (dt.Rows[i]["Value"].ToString() == "")
            //        {
            //            continue;
            //        }
            //        ArrayList list = new ArrayList();

            //        string timeStamp = DateTimeToUTC(Convert.ToDateTime(dt.Rows[i]["Time"].ToString())).ToString();
            //        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            //        long lTime = long.Parse(timeStamp + "0000000");
            //        TimeSpan toNow = new TimeSpan(lTime);
            //        DateTime dtResult = dtStart.Add(toNow);

            //        list.Add(Convert.ToInt64((dtResult - _sTime).TotalMilliseconds.ToString()));
            //        list.Add(Math.Round(Convert.ToDouble(dt.Rows[i]["Value"]), 2));
            //        arrList.Add(list);
            //    }
            //}

            //return arrList;
        }
        #endregion

        #region 一段时间频率
        public double[] GetFrec(string id, DateTime st, DateTime et, int count)
        {
            strSql = "select T_FRECTAG from T_BASE_POINTS_COMBINEBOX where T_BOXID='" + id + "'";
            obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            double[] val = null;

            if (obj != null && obj != DBNull.Value)
                val = (double[])iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValueByStep", new object[] { obj.ToString(), st, et, count });
            return val;
            //dt = (DataTable)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValueByStartTimeAndEndTime", new object[] { obj.ToString(), Convert.ToDateTime(st), Convert.ToDateTime(et) });
            //int num = 0;
            //if (dt.Rows.Count < count)
            //{
            //    num = 1;
            //}
            //else
            //{
            //    num = dt.Rows.Count / count;
            //}
            //ArrayList arrList = new ArrayList();
            //DateTime _sTime = new DateTime(1970, 1, 1);

            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    if (i % num == 0)
            //    {
            //        if (dt.Rows[i]["Value"].ToString() == "")
            //        {
            //            continue;
            //        }
            //        ArrayList list = new ArrayList();
            //        string timeStamp = DateTimeToUTC(Convert.ToDateTime(dt.Rows[i]["Time"].ToString())).ToString();
            //        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            //        long lTime = long.Parse(timeStamp + "0000000");
            //        TimeSpan toNow = new TimeSpan(lTime);
            //        DateTime dtResult = dtStart.Add(toNow);

            //        list.Add(Convert.ToInt64((dtResult - _sTime).TotalMilliseconds.ToString()));
            //        list.Add(Math.Round(Convert.ToDouble(dt.Rows[i]["Value"]), 2));
            //        arrList.Add(list);
            //    }
            //}

            //return arrList;
        }
        #endregion

        #region 获取电站下汇流箱
        public DataTable GetBox(string id)
        {
            strSql = @"select T_BOXID,T_BOXDESC_CN From T_BASE_COMBINEBOX where T_UNITID in (select T_UNITID from T_BASE_UNIT left join T_BASE_MACHINE on T_BASE_UNIT.T_MACHINEID = T_BASE_MACHINE.T_MACHINEID  where T_BASE_UNIT.T_DISTRICTID in (select T_DISTRICTID from T_BASE_DISTRICT where T_ORGID = '" + id + "') and T_BASE_MACHINE.T_TYPEID = 'nbq') order by T_ORDER desc";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            return dt;
        }
        #endregion

        #region 汇流箱详细信息
        public ArrayList GetBoxPointInfo(string id)
        {
            ArrayList list = new ArrayList();
            strSql = "select T_FIELD,T_DESC_CN,I_ORDER from T_BASE_COMBINEBOXINFO where T_BOXID='" + id + "' order by I_ORDER asc";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            if (dt == null || dt.Rows.Count == 0)
                return list;

            string columns = "";
            string[] name = new string[dt.Rows.Count];
            string[] points = new string[dt.Rows.Count];

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                name[i] = dt.Rows[i]["T_DESC_CN"].ToString();
                columns += dt.Rows[i]["T_FIELD"] + ",";
            }
            columns = columns.TrimEnd(',');
            strSql = "select " + columns + " from T_BASE_POINTS_COMBINEBOX where T_BOXID='" + id + "'";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                points[i] = dt.Rows[0][i].ToString();
            }
            list.Add(name);
            list.Add(points);

            return list;
        }
        #endregion

        #region  获取实时点数据
        public List<double[]> GetRealVal(string id, string[] name)
        {
            List<double[]> list = new List<double[]>();
            string column = "";
            string[] points = null;
            double[] val = null;
            for (int i = 0; i < name.Length; i++)
            {
                if (name[i] == "负荷")
                {
                    column += "T_PTAG,";
                }
                else if (name[i] == "电量")
                {
                    column += "T_EPTTAG,";
                }
                else if (name[i] == "状态")
                {
                    column += "T_STATETAG,";
                }
                else if (name[i] == "电压")
                {
                    column += "T_VoltageTAG,";
                }
                else if (name[i] == "电流")
                {
                    column += "T_CURRENTTAG,";
                }
            }

            if (column != "")
            {
                List<string> _points = new List<string>();
                column = column.Substring(0, column.Length - 1);

                string str_order = id.Replace("(", "").Replace(")", "").Replace("'", "");

                strSql = "select " + column + " from T_BASE_POINTS_COMBINEBOX where T_BOXID in(" + id + ") order by CHARINDEX(',' + LTRIM(T_BOXID) + ',', '," + str_order + ",')";


                dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
                if (dt != null && dt.Rows.Count > 0)
                {
                    points = new string[dt.Rows.Count];
                    val = new double[dt.Rows.Count];
                    for (int i = 0; i < name.Length; i++)
                    {
                        for (int k = 0; k < dt.Rows.Count; k++)
                        {
                            _points.Add(dt.Rows[k][i].ToString());

                        }
                    }
                    if (rtdbJudge == "1")
                        val = (double[])iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValues", new object[] { _points.ToArray() });
                    else
                        val = (double[])iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValuesNoJudge", new object[] { _points.ToArray() });
                    List<double> list_val = new List<double>(val);

                    for (int i = 0; i < name.Length; i++)
                    {
                        val = new double[dt.Rows.Count];
                        for (int k = 0; k < dt.Rows.Count; k++)
                        {
                            val[k] = list_val[0];
                            list_val.RemoveAt(0);
                        }
                        list.Add(val);
                    }
                }
            }
            return list;
        }

        #endregion

        #region 离散率曲线
        public double[][] GetDispersionRatioLine(string tag, DateTime sTime, DateTime eTime, int second)
        {
            //double[] val = null;
            //strSql = "select T_DISPERSIONRATIOTAG from T_BASE_POINTS_COMBINEBOX where T_BOXID='" + tag + "'";
            //obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });

            //if (obj != null && obj != DBNull.Value)
            //    val = (double[])iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValueByStep", new object[] { obj.ToString(), sTime, eTime, second });
            //return val;

            tag = tag.Replace("(", "").Replace(")", "").Replace("'", "");

            strSql = "select T_DISPERSIONRATIOTAG from T_BASE_POINTS_COMBINEBOX where T_BOXID in(" + tag + ")";

            double[][] val = null;

            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            string[] points = new string[dt.Columns.Count];

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                points[i] = dt.Rows[i][0].ToString();
            }
            val = (double[][])iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValuesByStep", new object[] { points, sTime, eTime, second });

            return val;
        }
        #endregion

        #region 支路电流 对比

        public double[][] GetBranchcurrent(string tag, DateTime sTime, DateTime eTime, int second)
        {
            //strSql = "select T_BRANCHCURRENT1TAG,T_BRANCHCURRENT2TAG,T_BRANCHCURRENT3TAG,T_BRANCHCURRENT4TAG,T_BRANCHCURRENT5TAG from T_BASE_POINTS_COMBINEBOX where T_UNITID in(" + tag + ")";
            strSql = "select T_CURRENTTAG from  T_BASE_POINTS_STRING where T_STRINGID in(" + tag + ")";
            double[][] val = null;

            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            string[] points = new string[dt.Rows.Count];

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                points[i] = dt.Rows[i][0].ToString();
            }
            val = (double[][])iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValuesByStep", new object[] { points, sTime, eTime, second });

            return val;
        }
        #endregion

    }
}
